package com.tansun.easycare.rule.datamodel.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.drools.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.rule.codeblock.entity.RuleCodeblock;
import com.tansun.easycare.rule.codeblock.model.CodeblockVO;
import com.tansun.easycare.rule.codeblock.service.RuleCodeblockService;
import com.tansun.easycare.rule.common.DataCache;
import com.tansun.easycare.rule.common.model.Item;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.common.model.RuleDataCollention;
import com.tansun.easycare.rule.common.model.RuleSetParamInfo;
import com.tansun.easycare.rule.common.service.DataBomService;
import com.tansun.easycare.rule.common.service.RuleDrlParseService;
import com.tansun.easycare.rule.common.service.RuleSetParmOperator;
import com.tansun.easycare.rule.common.service.impl.RuleBaseServiceImpl;
import com.tansun.easycare.rule.datamodel.dao.RuleDataDomainDao;
import com.tansun.easycare.rule.datamodel.dao.RuleDataparamsDao;
import com.tansun.easycare.rule.datamodel.entity.RuleDataDomain;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparamsInfo;
import com.tansun.easycare.rule.datamodel.entity.RuleDataset;
import com.tansun.easycare.rule.datamodel.service.DataModelService;
import com.tansun.easycare.rule.datamodel.service.RuleDataparamsService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.referencedata.entity.RuleReferenceData;
import com.tansun.easycare.rule.referencedata.service.RuleReferenceDataService;
import com.tansun.easycare.rule.rulegroup.service.RuleParseDrl;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;

/**
 * 数据集变量ServiceImpl
 *
 * @author lxs
 * @version 2017-02-17
 */
@Service("ruleDataparamsService")
public class RuleDataparamsServiceImpl extends RuleBaseServiceImpl<RuleDataparamsDao, RuleDataparams> implements RuleDataparamsService {

    @Autowired
    private RuleDataDomainDao ruleDataDomainDao;

    @Autowired
    private RuleDrlParseService ruleDrlParseService;
    
    public RuleDataparams get(String id) {
        return super.get(id);
    }
    
    @Autowired
    private DataBomService dataBomService;
    @Autowired
    RuleCodeblockService ruleCodeblockService;
    
    @Autowired
    private  RuleSetParmOperator  ruleSetParmOperator;

    @Override
    public void moveAttribute(String sourceId, String targetId, String attrName, String projectcode) throws Exception {
        RuleDataparams entity = new RuleDataparams();
        entity.setName(attrName);
        entity.setProjectcode(projectcode);
        entity.setDatasetId(sourceId);
        List<RuleDataparams> list = this.dao.findList(entity);
        RuleDataparams srcAttr = new RuleDataparams();
        BeanUtils.copyProperties(srcAttr, list.get(0));
        srcAttr.setDatasetId(targetId);
        entity.setId(list.get(0).getId());
        this.dao.delete(entity);
        srcAttr.setId(null);
        this.save(srcAttr);//移动到新数据集中先进行异常保存，产生新的id
        List<RuleDataparams> param = this.dao.findList(srcAttr);
        RuleDataparams paramdata = new RuleDataparams();
        BeanUtils.copyProperties(paramdata, param.get(0));
        if (com.tansun.rule.utils.StringUtils.isNotEmpty(srcAttr.getDomain())) {//枚举类型
            RuleDataDomain ruleDataDomain=new RuleDataDomain();
            ruleDataDomain.setDomainId(srcAttr.getDomain());
            List<RuleDataDomain> domainList = this.ruleDataDomainDao.findList(ruleDataDomain);//获取源数据枚举项
            for(RuleDataDomain d : domainList) {//更新枚举项
                RuleDataDomain doma = new RuleDataDomain();
                doma.setDomainId(paramdata.getId());
                doma.setId(d.getId());
                doma.setDomainValue(d.getDomainValue());
                doma.setName(d.getName());
                this.ruleDataDomainDao.update(doma);
            }
            paramdata.setDomain(paramdata.getId());
            this.save(paramdata);
        }
    }

    /**
     * 保存函数变量
     * @param ruleDataparams
     * @throws Exception 
     */
    public void saveFuncParam(RuleDataparams rulefuncparam) throws Exception {
    	RuleDataset ruleDataset = null;
    	if(!StringUtils.isEmpty(rulefuncparam.getId())) {
    		RuleDataparams tmp = this.get(rulefuncparam.getId());
    		ruleDataset = this.dataModelService.get(tmp.getDatasetId());
    	}else {
    		ruleDataset = this.dataModelService.get(rulefuncparam.getDatasetId());
    	}
    	RuleCodeblock funcBlock = new RuleCodeblock();
    	funcBlock.setId(rulefuncparam.getCodeblockId());
    	ResponseVO res = validate(rulefuncparam,ruleDataset.getName()+"_"+rulefuncparam.getName(),funcBlock);
    	if(res.getStatus()!=200){
    		throw new Exception(res.getDescription());
    	}
    	
    	RuleDataparams condition = new RuleDataparams();
    	condition.setDatasetId(ruleDataset.getId());
    	condition.setName(rulefuncparam.getName());
    	List<RuleDataparams> paramsList = this.findList(condition);
    	for (RuleDataparams ruleDataparams : paramsList) {
			if(StringUtils.isEmpty(rulefuncparam.getId())) {
				if(ruleDataparams.getName().equals(rulefuncparam.getName())) {
					throw new Exception("变量名已存在，请重新输入");
				}
			}else {
				if(ruleDataparams.getName().equals(rulefuncparam.getName()) && !ruleDataparams.getId().equals(rulefuncparam.getId())) {
					throw new Exception("变量名已存在，请重新输入");
				}
			}
		}
    	rulefuncparam.setDatasetId(ruleDataset.getId());
    	rulefuncparam.setIsfuncparam("1");
    	rulefuncparam.setIsCollections("false");
    	rulefuncparam.setIsDerives("false");
    	rulefuncparam.setIsout("false");
    	this.save(rulefuncparam);
    	funcBlock.setParameterId(rulefuncparam.getId());
    	funcBlock.setProjectCode(rulefuncparam.getProjectcode());
        String funcBlockId =funcBlock.getId();
        if(StringUtils.isEmpty(funcBlockId)){
            funcBlock.setActiveStatus("1");
        }else{
            RuleCodeblock rcb = new RuleCodeblock();
            rcb.setProjectCode(rulefuncparam.getProjectcode());
            rcb.setId(funcBlockId);
            List<RuleCodeblock> rcbs = this.ruleCodeblockService.findList(rcb);
            String activeStatus = rcbs.get(0).getActiveStatus();
            if(StringUtils.isEmpty(activeStatus)||"3".equals(activeStatus)){//旧数据默认已审核已生效
                funcBlock.setActiveStatus("2");
            }
        }
        funcBlock.setCodeBodyEdit(funcBlock.getCodeBody());
        funcBlock.setFormatcodebodyEdit(funcBlock.getFormatcodebody());
        //新增或者修改时候，已生效版字段不存值
        funcBlock.setCodeBody(null);
        funcBlock.setFormatcodebody(null);
    	ruleCodeblockService.save(funcBlock);
		// 收集引用数据
		Map<String, RuleReferenceData> ruleRefMap = new HashMap<String, RuleReferenceData>();
        try {
        	RuleManage funcRuleManage = new RuleManage();
        	funcRuleManage.setProjectCode(rulefuncparam.getProjectcode());
        	funcRuleManage.setId(rulefuncparam.getId());
        	funcRuleManage.setCode(funcBlock.getModelCode());
        	funcRuleManage.setModelType(funcBlock.getModelType());
			ruleDrlParseService.collectReferenceData(funcRuleManage, funcBlock.getCodeBodyEdit(), ruleRefMap);
			RuleReferenceData arg0 = new RuleReferenceData();
			arg0.setManageId(rulefuncparam.getId());
			this.ruleReferenceDataService.deleteByManage(arg0);
			// 保存数据数据
			this.ruleReferenceDataService.saveReferenceData(ruleRefMap);
			ruleCodeblockService.saveProjectFunc(rulefuncparam.getProjectcode());
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    
    public ResponseVO validate(RuleDataparams rulefuncparam,String functionName,RuleCodeblock funcBlock) throws Exception {
    	ResponseVO res = new ResponseVO();
		List<String[]> fplist = new ArrayList<String[]>();
    	String[] arg0 = {"参数0","Map","dataMap"};
    	fplist.add(arg0);
    	String[] arg1 = {"参数1","Map","metaMap"};
    	fplist.add(arg1);
    	funcBlock.setFunctionName(functionName);
    	funcBlock.setParameters(JSON.toJSONString(fplist));
    	funcBlock.setReturnType(rulefuncparam.getReturnType());
    	funcBlock.setInitcode("RuleHelper ruleHelper = new RuleHelper(metaMap);");
    	funcBlock.setFuncImport(rulefuncparam.getFuncImport());
    	funcBlock.setFormatcodebody(rulefuncparam.getFormatcodebody());
    	if("format".equals(rulefuncparam.getFuncImport())) {
            RuleParseDrl ruleParseDrl = ruleDrlParseService.getParseObj(rulefuncparam.getProjectcode());
            //设置action
            List<String> actionDivs = new ArrayList<String>();
            ruleParseDrl.getListDivStr(actionDivs, rulefuncparam.getFormatcodebody());
            String codeBody = "";
            for (String spans : actionDivs) {
                List<Map<String, String>> list = new ArrayList<Map<String, String>>();
                ruleParseDrl.getListSpanMap(list, spans);
                codeBody += ruleParseDrl.funcActionHandler(list);
            }
        	funcBlock.setCodeBody(codeBody);
        	funcBlock.setStrCodeBody(codeBody);
    	}else {
        	funcBlock.setCodeBody(rulefuncparam.getCodeBody());
        	funcBlock.setStrCodeBody(funcBlock.getCodeBody());
    	}
    	CodeblockVO codeblockVO = new CodeblockVO();
    	codeblockVO.setProjectCode(rulefuncparam.getProjectcode());
    	codeblockVO.setRuleCodeblock(funcBlock);
    	codeblockVO.setFuncParams(JSON.toJSONString(fplist));
    	res = ruleCodeblockService.validateDrl(codeblockVO,true);
    	return res;
    }
    
    public List<RuleDataparams> findList(RuleDataparams ruleDataparams) {
        return super.findList(ruleDataparams);
    }

    public PageInfo<RuleDataparams> findPage(Page<RuleDataparams> page, RuleDataparams ruleDataparams) {
    	ruleDataparams.setPage(page);
    	 PageInfo<RuleDataparams>  pageInfo  = new PageInfo<>(this.dao.findListNoFuncparam(ruleDataparams));
        return pageInfo;
    }


    public void save(RuleDataparams ruleDataparams) {
        super.save(ruleDataparams);
    }

    public void delete(RuleDataparams ruleDataparams) {
        super.delete(ruleDataparams);
    }

    @Override
    public List<RuleDataDomain> findDataDomainList(RuleDataDomain ruleDataDomain) {
        return this.ruleDataDomainDao.findList(ruleDataDomain);
    }
    
    /**
     * 查询
     * @param domainIds 
     */
    @Override
    public List<RuleDataDomain> findDataDomainListByDomainIds(List<String> domainIds) throws BizException {
		if( domainIds!=null && !domainIds.isEmpty() ) {
			Map<String,Object> map =  new HashMap<>();
			map.put("domainIds", domainIds);
			return this.ruleDataDomainDao.findListByDomainIds(map);
		}else {
			return new ArrayList<RuleDataDomain>();
		}
    }

    /**
     * @param ruleDataparams 变量信息
     * @param domainDataStr  枚举值列表信息
     */
    public void saveParamsAndDomain(RuleDataparams ruleDataparams, String domainDataStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!StringUtils.isEmpty(ruleDataparams.getId())) {
            map.put("ids", Arrays.asList(ruleDataparams.getId()));
            this.ruleDataDomainDao.deleteByDomainIds(map);
        } else {
            super.save(ruleDataparams);
        }

        List<Item> list = JSONArray.parseArray(domainDataStr, Item.class);
        StringBuffer domain = new StringBuffer("[");
        StringBuffer dValue = new StringBuffer("[");
        Map<String, String> validateMap;
        if (list != null && list.size() > 0) {
            validateMap = validateUnique(list);
            if (validateMap == null) {
                for (Item i : list) {
                    RuleDataDomain d = new RuleDataDomain();
                    d.setDomainId(ruleDataparams.getId());
                    d.setName(i.getName());
                    d.setDomainValue(i.getValue());
                    d.preInsert();
                    ruleDataDomainDao.insert(d);
                }
                domain.append(list.get(0).getName());
                dValue.append(list.get(0).getValue());
                if (list.size() > 1) {
                    for (int i = 1; i < list.size(); i++) {
                        domain.append(",").append(list.get(i).getName());
                        dValue.append(",").append(list.get(i).getValue());
                    }
                }
                domain.append("]");
                dValue.append("]");
                ruleDataparams.setDomainStr(domain.toString());
                ruleDataparams.setDomain(ruleDataparams.getId());
                DataCache.enumChange(ruleDataparams.getProjectcode());
            } else {
                if (validateMap.containsKey("name")) {
                    throw new BizException("", "中文名:[" + validateMap.get("name") + "]存在重复");
                } else if (validateMap.containsKey("value")) {
                    throw new BizException("", "码值:[" + validateMap.get("value") + "]存在重复");
                }
            }
        }
        super.save(ruleDataparams);
    }

    /**
     * @param ruleDataparams 变量信息
     * @param domainDataStr  枚举值列表信息
     */
    @Override
	public void saveParamsAndDomain(RuleDataparams ruleDataparams, List<Item> list)  throws Exception{
		// TODO Auto-generated method stub
    	Map<String, Object> map = new HashMap<String, Object>();
        if (!StringUtils.isEmpty(ruleDataparams.getId())) {
            map.put("ids", Arrays.asList(ruleDataparams.getId()));
            this.ruleDataDomainDao.deleteByDomainIds(map);
        } else {
            super.save(ruleDataparams);
        }
        StringBuffer domain = new StringBuffer("[");
        StringBuffer dValue = new StringBuffer("[");
        Map<String, String> validateMap;
        if (list != null && list.size() > 0) {
            validateMap = validateUnique(list);
            if (validateMap == null) {
                for (Item i : list) {
                    RuleDataDomain d = new RuleDataDomain();
                    d.setDomainId(ruleDataparams.getId());
                    d.setName(i.getName());
                    d.setDomainValue(i.getValue());
                    d.preInsert();
                    ruleDataDomainDao.insert(d);
                }
                domain.append(list.get(0).getName());
                dValue.append(list.get(0).getValue());
                if (list.size() > 1) {
                    for (int i = 1; i < list.size(); i++) {
                        domain.append(",").append(list.get(i).getName());
                        dValue.append(",").append(list.get(i).getValue());
                    }
                }
                domain.append("]");
                dValue.append("]");
                ruleDataparams.setDomainStr(domain.toString());
                ruleDataparams.setDomain(ruleDataparams.getId());
                DataCache.enumChange(ruleDataparams.getProjectcode());
            } else {
                if (validateMap.containsKey("name")) {
                    throw new BizException("", "中文名:[" + validateMap.get("name") + "]存在重复");
                } else if (validateMap.containsKey("value")) {
                    throw new BizException("", "码值:[" + validateMap.get("value") + "]存在重复");
                }
            }
        }
        if (!StringUtils.isEmpty(ruleDataparams.getId())) {
        	RuleDataparams  preRuleDataparam = this.dao.get(ruleDataparams.getId());
        	if (!preRuleDataparam.getName().equals(ruleDataparams.getName())) {
        		RuleSetParamInfo  oldParamInfo = new  RuleSetParamInfo();
        		oldParamInfo.setCode(preRuleDataparam.getName());
        		oldParamInfo.setName(preRuleDataparam.getChzn());
        		RuleSetParamInfo  newParamInfo = new  RuleSetParamInfo();
        		newParamInfo.setCode(ruleDataparams.getName());
        		newParamInfo.setName(ruleDataparams.getChzn());
        		this.ruleSetParmOperator.upateRuleModel(preRuleDataparam.getProjectcode(), newParamInfo, oldParamInfo, false); 
        	}
        }
        super.save(ruleDataparams);
	}

	/**
     * 校验是否重复
     *
     * @param itemList 枚举值列表
     * @return 是否唯一
     */
    private Map<String, String> validateUnique(List<Item> itemList) {
        Map<String, String> map = new HashMap<String, String>();

        if (itemList.size() == 1) {
            return null;
        }
        for (int i = 0; i < itemList.size(); i++) {
            for (int j = i + 1; j < itemList.size(); j++) {
                if (itemList.get(i).getName().equals(itemList.get(j).getName())) {
                    map.put("name", itemList.get(i).getName());
                    return map;
                }
                if (itemList.get(i).getValue().equals(itemList.get(j).getValue())) {
                    map.put("value", itemList.get(i).getValue());
                    return map;
                }
            }
        }
        return null;
    }

    @Autowired
    RuleReferenceDataService ruleReferenceDataService;
    @Autowired
    DataModelService dataModelService;
    @Override
    public void deleteRuleDataparamsById(String id) throws BizException {
        RuleDataparams rdp = this.get(id); 
        RuleDataset rds = dataModelService.get(rdp.getDatasetId());
    	RuleReferenceData condition=new RuleReferenceData(); //实例化rule_reference_data
    	condition.setProjectCode(rdp.getProjectcode());//获取rule_dataset 的ProjectCode
    	condition.setClassName(rds.getName());  //获取rule_dataset的name
    	condition.setNameen(rdp.getName());
    	List<RuleReferenceData> refList = ruleReferenceDataService.findReferenceParamList(condition);
        if(refList!=null && refList.size()>0){
        	throw new BizException("E-200003");
    	}else{
        	 RuleDataparams dp = new RuleDataparams();
             dp.setId(id);
             this.dao.deleteflag(dp);
        }
    }

    @Override
    public List<RuleDataparams> findRuleDataparamsByMap(Map<String, Object> map) {
        return this.dao.findParmByClassName(map);
    }

    public void insertBatchDomains(List<RuleDataDomain> list) {
        if (list == null || list.size() == 0)
            return;
        RuleDataDomain con = new RuleDataDomain();
        for (RuleDataDomain ruleDataDomain : list) {
            if (StringUtils.isEmpty(ruleDataDomain.getId())) {
                con.setId(ruleDataDomain.getId());
                ruleDataDomainDao.delete(con);
            }
        }
        try {
            RuleDataCollention<RuleDataDomain> ruleData = new RuleDataCollention<RuleDataDomain>();
            ruleData.setList(list);
            ruleDataDomainDao.insertBatch(ruleData);
        } catch (Exception e) {
            throw new BizException(e, "");
        }
    }
	public Map<String,String>  getdataparams(String projectCode) {
		Map<String,String> ruleParseDrl = new HashMap<String,String>();
    	String cacheKey = DataCache.getCacheKey(projectCode, DataCache.RULEPARSEDRL_OPTION);
    	if(DataCache.canGetFromCache(cacheKey)) {
			ruleParseDrl = (Map<String, String>) DataCache.getValue(cacheKey);
    	}else {
			RuleDataset dsCon = new RuleDataset();
			dsCon.setProjectcode(projectCode);
			List<RuleDataset> dsList = dataModelService.findList(dsCon);
			for (RuleDataset ruleDataset : dsList) {
				RuleDataparams condition = new RuleDataparams();
				condition.setDatasetId(ruleDataset.getId());
				List<RuleDataparams> paramList = this.findList(condition);
				for (RuleDataparams ruleDataparams : paramList) {
					if("1".equals(ruleDataparams.getIsfuncparam())) {
						RuleCodeblock codeCon = new RuleCodeblock();
						codeCon.setParameterId(ruleDataparams.getId());
						List<RuleCodeblock> codeList = ruleCodeblockService.findList(codeCon);
						if(codeList.size()>0) {
							ruleParseDrl.put(ruleDataset.getName()+"."+ruleDataparams.getName(), codeList.get(0).getFunctionName()+"(dataMap,metaMap)");
	//						dataMap.put(ruleDataset.getName()+ruleDataparams.getName(), codeList.get(0).getFunctionName()+"()");
						}
					}
				}
			}
			DataCache.setValue(cacheKey, ruleParseDrl);
    	}
		return ruleParseDrl;
	}


	@Override
	public List<RuleDataparams> findFunctionParam(Map<String, String> map) {
		
		return this.dao.findFunctionParam(map);
	}


	@Override
	public List<String> findClassParam(Map<String, String> map) {
		// TODO Auto-generated method stub
		return  this.dao.findClassParam(map);
	}


	@Override
	public Map<String, String> findParamMap(Map<String, String> map) {
		// TODO Auto-generated method stub
		return this.dao.findParamMap(map);
	}


	@Override
	public List<RuleDataparams> findParmByClassName(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return this.dao.findParmByClassName(map);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String,RuleDataparams> findParamsKeyClassNameDotNameByProjectCode(String projectCode) {
		Map<String,RuleDataparams> className2RDP = null;
        String cacheKey = DataCache.getCacheKey(projectCode, DataCache.RULEDATAPARAMS_MAP_OPTION);
        if( DataCache.canGetFromCache(cacheKey) ) {
        	className2RDP = (Map<String, RuleDataparams>) DataCache.getValue(cacheKey);
        }else {
        	className2RDP = new HashMap<String,RuleDataparams>();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("projectcode",projectCode);
            List<RuleDataparams> list = this.findParmByClassName(map);
            Map<String, List<RuleDataparams>> mapList = new HashMap<String, List<RuleDataparams>>();
            List<RuleDataparams> rdps = null;
            for(RuleDataparams rdp:list) {
            	String key = rdp.getClassName() + "." + rdp.getName();
            	className2RDP.put(key, rdp);
            	String key2 = rdp.getDatasetId();
            	if( mapList.containsKey(key2) ) {
            		rdps = mapList.get(key2);
            	}else {
            		rdps = new ArrayList<>();
            		mapList.put(key2, rdps);
            	}
            	rdps.add(rdp);
            }
            DataCache.setValue(cacheKey, className2RDP);
            DataCache.setValue(DataCache.getCacheKey(projectCode, DataCache.RULEDATAPARAMS_LIST_OPTION), mapList);
        }
		return className2RDP;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, List<RuleDataparams>> findParamsKeyDsetIdByProjectCode(String projectCode) {
		Map<String, List<RuleDataparams>> mapList = null;
        String cacheKey = DataCache.getCacheKey(projectCode, DataCache.RULEDATAPARAMS_LIST_OPTION);
        if( DataCache.canGetFromCache(cacheKey) ) {
        	mapList = (Map<String, List<RuleDataparams>>) DataCache.getValue(cacheKey);
        }else {
        	mapList = new HashMap<String, List<RuleDataparams>>();
        	
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("projectcode",projectCode);
            List<RuleDataparams> list = this.findParmByClassName(map);
            Map<String,RuleDataparams> className2RDP = new HashMap<String,RuleDataparams>();
            List<RuleDataparams> rdps = null;
            for(RuleDataparams ruleDataparams:list) {
            	String key = ruleDataparams.getClassName() + "." + ruleDataparams.getName();
            	className2RDP.put(key, ruleDataparams);
            	String key2 = ruleDataparams.getDatasetId();
            	if( mapList.containsKey(key2) ) {
            		rdps = mapList.get(key2);
            	}else {
            		rdps = new ArrayList<>();
            		mapList.put(key2, rdps);
            	}
            	rdps.add(ruleDataparams);
            }
            DataCache.setValue(cacheKey, mapList);
            DataCache.setValue(DataCache.getCacheKey(projectCode, DataCache.RULEDATAPARAMS_MAP_OPTION), className2RDP);
        }
        return mapList;
	}
    @Override
    public void complementApproval(List<String> ids) {
        String projectCode = "";
        for(String id : ids){
            RuleCodeblock ruleCodeblock = new RuleCodeblock();
            ruleCodeblock.setId(id);
            List<RuleCodeblock> list = ruleCodeblockService.findList(ruleCodeblock);
            RuleCodeblock rc = list.get(0);
            rc.setCodeBody(rc.getCodeBodyEdit());
            rc.setFormatcodebody(rc.getFormatcodebodyEdit());
            rc.setActiveStatus("3");
//            rc.setCodeBodyEdit(null);
//            rc.setFormatcodebodyEdit(null);
            ruleCodeblockService.save(rc);
            String parameterId = rc.getParameterId();
            RuleDataparams ruleDataparam = new RuleDataparams();
            ruleDataparam.setId(parameterId);
            RuleDataparams rd = this.dao.get(parameterId);
            // 收集引用数据
            Map<String, RuleReferenceData> ruleRefMap = new HashMap<String, RuleReferenceData>();
            try {
                RuleManage funcRuleManage = new RuleManage();
                funcRuleManage.setProjectCode(rd.getProjectcode());
                funcRuleManage.setId(rd.getId());
                funcRuleManage.setCode(rc.getModelCode());
                funcRuleManage.setModelType(rc.getModelType());
                ruleDrlParseService.collectReferenceData(funcRuleManage, rc.getCodeBody(), ruleRefMap);
                RuleReferenceData arg0 = new RuleReferenceData();
                arg0.setManageId(rd.getId());
                this.ruleReferenceDataService.deleteByManage(arg0);
                // 保存数据数据
                this.ruleReferenceDataService.saveReferenceData(ruleRefMap);
                ruleCodeblockService.saveProjectFunc(rd.getProjectcode());
                projectCode=rd.getProjectcode();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(!StringUtils.isEmpty(projectCode)){
            //清楚缓存
            DataCache.funcParamChange(projectCode);
        }
    }

    @Override
    public List<RuleDataparamsInfo> findListWithStatus(RuleDataparamsInfo rd) {
        return this.dao.findListWithStatus(rd);
    }


	@Override
	public void deleteRuleDataparamsByIds(List<String> ids) throws BizException {
		// TODO Auto-generated method stub
		if( ids!=null && ids.size()>0 ) {
			Map<String,Object> map =  new HashMap<>();
			map.put("ids", ids);
			this.dao.deleteRuleDataparamsByIds(map);
			ruleDataDomainDao.deleteByDomainIds(map);
		}

	}

	 void update(RuleDataparams arg0) {
		 this.dao.update(arg0);
	 }
	@Override
	public void updateDataSetId(String oldDataSetId,String newDataSetId) {
		Map<String,String> map = new HashMap<String,String>();
		map.put("oldDataSetId", oldDataSetId);
		map.put("newDataSetId", newDataSetId);
		this.dao.updateDataSetId(map);
	}
    /**
     * 更新关联层级ID（初始化）
     * @param condition
     * @return
     */
    public int updateRankId(RuleDataparams condition) {
    	return this.dao.updateRankId(condition);
    }

	@Override
	public void updatParam(List<RuleDataparams> list) {
		if( list!=null && list.size()>0 ) {
			for(int i=0;i<list.size();i++) {
				RuleDataparams entity = new RuleDataparams();
				entity=list.get(i);
				this.dao.update(entity);
			}
		}
		
	}

	@Override
	public PageInfo<RuleDataparamsInfo> findFuncParamPage(Page<RuleDataparamsInfo> page,
			RuleDataparamsInfo ruleDataparamsInfo) {
		//查询当前项目的函数变量
		 PageInfo<RuleDataparamsInfo> pageInfo = new PageInfo<>(this.dao.findListWithStatus(ruleDataparamsInfo));
		return pageInfo;
	}

	@Override
	public List<RuleDataparams> queryRuleDataList(RuleDataparams ruleparams) {
		return this.dao.queryRuleDataList(ruleparams);
	}

	@Override
	public List<RuleDataparams> findChznList(RuleDataparams ruleparams) {
		return this.dao.findChznList(ruleparams);
	}

	@Override
	public void saveAndUpdateRef(RuleDataparams ruleDataparams) throws Exception {
        if (!StringUtils.isEmpty(ruleDataparams.getId())) {
        	RuleDataparams  preRuleDataparam = this.dao.get(ruleDataparams.getId());
        	if (!preRuleDataparam.getName().equals(ruleDataparams.getName())) {
        		RuleSetParamInfo  oldParamInfo = new  RuleSetParamInfo();
        		oldParamInfo.setCode(preRuleDataparam.getName());
        		oldParamInfo.setName(preRuleDataparam.getChzn());
        		RuleSetParamInfo  newParamInfo = new  RuleSetParamInfo();
        		newParamInfo.setCode(ruleDataparams.getName());
        		newParamInfo.setName(ruleDataparams.getChzn());
        		this.ruleSetParmOperator.upateRuleModel(preRuleDataparam.getProjectcode(), newParamInfo, oldParamInfo, false); 
        	}
        }
        super.save(ruleDataparams);
		
	}
	
	
}